package mock;

import lombok.Data;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * Created by Crowhyc on 2016/5/23.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
        @ContextConfiguration(locations = "classpath:spring/*.xml")
})
@Data
public abstract class BeforeTester {
    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;
    private String token;

    @Before
    public void setUp() throws Exception {
//        SpringUtils.setApplicationContext(wac);
//        HashSet<BaseDomainService> baseDomainServices = (HashSet<BaseDomainService>) SpringUtils.getInstances(BaseDomainService.class);
//        for (BaseDomainService ret : baseDomainServices) {
//            ret.setContext(SpringUtils.getInstance(ServiceContext.class));
//        }
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
        login();
    }

    private void login() throws Exception {
        UserLogin userLogin = new UserLogin();
        MvcResult result = mockMvc.
                perform(MockMvcRequestBuilders.post(userLogin.getUrl()).param("username", "admin").param("password", "123456")).andDo(MockMvcResultHandlers.print()).andReturn();
        JSONObject object = new JSONObject(result.getResponse().getContentAsString());
        token = object.getString("Data");

    }

    //<editor-fold desc="getter/setter">
    public ResultActions getMockMvcResult(MockHttpServletRequestBuilder builders) throws Exception {
        return mockMvc.perform(builders.header("token", token));
    }

    public void setMockMvc(MockMvc mockMvc) {
        this.mockMvc = mockMvc;
    }

    public WebApplicationContext getWac() {
        return wac;
    }

    public void setWac(WebApplicationContext wac) {
        this.wac = wac;
    }
    //</editor-fold>


}
